﻿using System;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using SevenDigital.EndUserManagement.Core.Exceptions;

namespace SevenDigital.EndUserManagement.Core.Repository
{
	public sealed class UserRepository : BaseRepository<User, Int32>, IUserRepository
	{
		public UserRepository(ISessionFactory sessionFactory) : base(sessionFactory) {}

		public User FindUserByEmail(string emailAddress) {
			try {
				var query = Session.Linq<User>()
					.Where(x => x.Email == emailAddress)
					.OrderByDescending(x => x.Id);

				//var query = from user in Session.Linq<User>()
				//            where user.Email == emailAddress
				//            orderby user.Id descending
				//            select user;

				return query.First();
			} catch (InvalidOperationException) {
				throw new EntityNotFoundException("No user found");
			}
		}
	}
}